<template>
    <div class="attribute-history-modal-wrapper" ref="attributeHistoryModalRef">
        <el-dialog :model-value="props.value" :title="dialog.title" :width="dialog.width" destroy-on-close>
            <template #header>
                <div class="el-dialog__title">
                    <span>{{ dialog.title }}</span>
                    <span
                        v-if="rowList && tableSelect && tableSelect.length !== rowList.length"
                        style="color: #999; font-size: 12px; margin-left: 10px"
                    >
                        注：仅展示可写的属性，只读属性不展示！
                    </span>
                </div>
            </template>
            <el-form ref="ruleFormRef" :model="formData" :rules="ruleForm" label-width="80px">
                <el-row v-for="(item, index) in formData.attrs" :key="index">
                    <el-col :span="8">
                        <el-form-item label="属性名称">
                            <el-input :value="item.displayName" disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="所属设备/组件" label-width="110px">
                            <el-input :value="item.showName" disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="属性值" required class="trigger-condition-form-item" prop="attrs">
                            <el-input
                                v-if="item.dataType === 'NUMBER'"
                                v-model="item.setValue"
                                @input="value => (item.setValue = value.replace(/[^0-9.eE+-]/g, ''))"
                                :class="{ error: !item.setValue }"
                                placeholder="请输入默认值"
                                maxlength="50"
                            />
                            <el-date-picker
                                v-else-if="item.dataType === 'DATE'"
                                :class="{ error: !item.setValue }"
                                v-model="item.setValue"
                                type="datetime"
                                value-format="YYYY-MM-DD HH:mm:ss"
                                placeholder="请选择默认时间"
                            />
                            <el-radio-group
                                v-else-if="item.dataType === 'BOOLEAN'"
                                v-model="item.setValue"
                                :class="{ error: !item.setValue }"
                            >
                                <el-radio :value="true">true</el-radio>
                                <el-radio :value="false">false</el-radio>
                            </el-radio-group>
                            <el-input
                                v-else
                                v-model="item.setValue"
                                :class="{ error: !item.setValue }"
                                placeholder="请输入默认值"
                                maxlength="50"
                            />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="props.close">取消</el-button>
                    <el-button type="primary" @click="submitForm" :loading="loading">确定</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>
<script setup lang="ts">
import type { FormInstance, FormRules } from 'element-plus';
import { IoTDeviceService } from '@great/services';
import { reactive } from 'vue';
import type { PopupBoxProps } from '@great/utils';
import { useRequest } from 'vue-request';

interface IProps extends PopupBoxProps {
    rowList: Array<Record<string, any>>;
    tableSelect?: Array<Record<string, any>>;
    deviceDetail: Record<string, any>;
    callBack?: () => Promise<void>;
}
const props = defineProps<IProps>();

interface Dialog {
    title: string;
    width: number;
    detail?: Array<Record<string, any>>;
}
const dialog = reactive<Dialog>({
    title: '下发属性值',
    width: 900,
    detail: undefined
});

const formData = reactive<any>({
    attrs: []
});
const ruleFormRef = useTemplateRef<FormInstance>('ruleFormRef');
const attributeHistoryModalRef = useTemplateRef('attributeHistoryModalRef');
const ruleForm = reactive<FormRules<any>>({
    attrs: [
        {
            validator: (rule: any, value: any, callback: any) => {
                if (attributeHistoryModalRef.value?.querySelector('.error')) {
                    return callback(new Error('请输入默认值'));
                }
                return callback();
            },
            trigger: ['blur', 'change']
        }
    ]
});

// 提交接口请求
const { run, loading } = useRequest(
    () => {
        return IoTDeviceService.attributeWrite({
            proDeviceNo: props.deviceDetail?.deviceNo,
            productObject: props.deviceDetail?.objectName,
            attrs: formData.attrs.map((item: any) => ({
                objectName: item.objectName,
                attributeName: item.attributeName,
                deviceNo: item.deviceNo,
                value: item.setValue
            }))
        });
    },
    {
        manual: true,
        onSuccess(res) {
            ElNotification({
                title: '下发成功！',
                type: 'success'
            });
            closeDialog();
        }
    }
);
// 表单提交
const submitForm = () => {
    ruleFormRef.value?.validate(valid => {
        valid && run();
    });
};

//关闭弹框
const closeDialog = () => {
    props.close();
    props.callBack?.();
};
// 打开弹框
const openDialog = () => {
    formData.attrs = JSON.parse(JSON.stringify(props.rowList)).map((item: any) => ({
        ...item,
        setValue: String(item.setValue || '')
    }));
};

const init = () => {
    openDialog();
};
init();
</script>
<style scoped lang="scss">
.attribute-history-modal-wrapper {
    .el-form {
        max-height: 600px;
        overflow: auto;
        padding-right: 5px;
        .el-input-number {
            width: 100%;
        }
        :deep(.trigger-condition-form-item.is-error) {
            .el-form-item__content {
                border: none;
                border-radius: 0;
                padding: 0;
            }
            .el-select__wrapper,
            .el-input__wrapper {
                box-shadow: 0 0 0 1px var(--el-border-color) inset !important;
            }
            .el-input + .el-form-item__error {
                display: none;
            }
            .el-input.error {
                .el-input__wrapper {
                    box-shadow: 0 0 0 1px var(--el-color-danger) inset !important;
                }
            }
            .el-select.error {
                .el-select__wrapper {
                    box-shadow: 0 0 0 1px var(--el-color-danger) inset !important;
                }
            }
            .el-input.error + .el-form-item__error,
            .el-select.error + .el-form-item__error {
                display: block;
            }
        }
    }
}
</style>
